package org.bee.controller;

import jakarta.annotation.Resource;
import org.bee.PageUtil;
import org.bee.ResultTool;
import org.bee.enums.IsDelete;
import org.bee.enums.ResultCode;
import org.bee.exception.ExceptionUtils;
import org.bee.id.UUIDUtils;
import org.bee.input.RoleInsertVo;
import org.bee.input.RoleSearchVo;
import org.bee.input.RoleUpdateVo;
import org.bee.model.AdminUserExample;
import org.bee.model.Role;
import org.bee.model.RoleExample;
import org.bee.model.result.Result;
import org.bee.output.RoleOut;
import org.bee.secuirty.annotation.ApiAuth;
import org.bee.secuirty.context.CurrentUser;
import org.bee.service.AdminUserService;
import org.bee.service.RoleElementService;
import org.bee.service.RolePermissionService;
import org.bee.service.RoleService;
import org.bee.transaction.TransUtils;
import org.bee.transaction.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 角色控制器
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    Logger logger = LoggerFactory.getLogger(RoleController.class);

    @Resource
    RoleService roleService;

    @Resource
    private AdminUserService adminUserService;

    @Resource
    private RolePermissionService rolePermissionService;

    @Resource
    private RoleElementService roleElementService;
    /**
     * 分页查询角色
     * @param roleSearchVo 查询条件
     * @return 角色列表
     */
    @PostMapping("rolePage")
    @ApiAuth(value = "role.pageQuery",description = "角色分页查询")
    public Result rolePage(@RequestBody RoleSearchVo roleSearchVo){
        Result result = ResultTool.success();
        PageUtil.setPage(roleSearchVo.getCurrent(),roleSearchVo.getSize());
        List<Role> select = roleService.select(roleSearchVo);
        List<RoleOut> resultList = new ArrayList<>();
        select.forEach(role -> {
            RoleOut roleOut = new RoleOut();
            BeanUtils.copyProperties(role,roleOut);
            resultList.add(roleOut);
        });
        result.setPageData(resultList);
        return result;
    }


    /**
     * 根据id查询角色
     * @param id 角色id
     * @return 角色信息
     */
    @GetMapping("selectById")
    @ApiAuth(value = "role.selectById",description = "角色根据id查询")
    public Result selectById(String id) {
        Result result = ResultTool.success();
        if(id == null || id.isEmpty()){
            return ResultTool.fail(ResultCode.PARAM_NOT_COMPLETE);
        }
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andRoleIdEqualTo(id);
        criteria.andIsDeletedEqualTo(IsDelete.FALSE.getCode());
        List<Role> roles = roleService.selectByExample(roleExample);
        if (roles.isEmpty()) {
            return ResultTool.fail(ResultCode.DATA_NULL);
        }
        Role first = roles.getFirst();
        RoleOut roleOut = new RoleOut();
        BeanUtils.copyProperties(first, roleOut);
        result.setData(roleOut);
        return result;
    }

    /**
     * 添加角色
     * @param roleInsertVo 添加角色信息
     * @return 结果
     */
    @PostMapping("insert")
    @ApiAuth(value = "role.insert",description = "角色新增")
    public Result insert(@RequestBody RoleInsertVo roleInsertVo) {
        Result result = ResultTool.success();
        if(roleInsertVo == null){
            return ResultTool.fail(ResultCode.PARAM_NOT_COMPLETE);
        }
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andRoleCodeEqualTo(roleInsertVo.getRoleCode());
        criteria.andIsDeletedEqualTo(IsDelete.FALSE.getCode());
        List<Role> roles = roleService.selectByExample(roleExample);
        if (!roles.isEmpty()) {
            result = ResultTool.fail(ResultCode.DATA_REPEAT);
            result.setMsg(roleInsertVo.getRoleCode()+"已存在");
            return result;
        }
        Transaction trans = null;
        try {
            Role role = new Role();
            BeanUtils.copyProperties(roleInsertVo, role);
            role.setRoleId(UUIDUtils.simpleUuid());
            role.setCreateUserId(CurrentUser.getUser().getUserId());
            role.setCreateTime(new Date());
            role.setIsDeleted(IsDelete.FALSE.getCode());
            trans= TransUtils.getTrans();
            trans.begin();
            roleService.insert(role);
            trans.commit();
        } catch (Exception e) {
            TransUtils.rollback(trans);
            result = ResultTool.fail();
            logger.error(e.getMessage(), ExceptionUtils.getFullStackTrace(e));
            return result;
        }
        return result;
    }

    /**
     * 修改角色
     * @param roleUpdateVo 修改角色信息
     * @return 修改结果
     */
    @PostMapping("update")
    @ApiAuth(value = "role.update",description = "角色修改")
    public Result update(@RequestBody RoleUpdateVo roleUpdateVo) {
        Result result = ResultTool.success();
        if(roleUpdateVo == null){
            return ResultTool.fail(ResultCode.PARAM_NOT_COMPLETE);
        }
        Transaction trans = null;
        try {
            Role role = new Role();
            BeanUtils.copyProperties(roleUpdateVo,role);
            role.setUpdateUserId(CurrentUser.getUser().getUserId());
            role.setUpdateTime(new Date());
            trans= TransUtils.getTrans();
            trans.begin();
            roleService.update(role);
            trans.commit();
        } catch (Exception e) {
            TransUtils.rollback(trans);
            result = ResultTool.fail();
            logger.error(e.getMessage(), ExceptionUtils.getFullStackTrace(e));
            return result;
        }
        return result;
    }

    /**
     * 删除角色
     * @param id 角色id
     * @return 删除结果
     */
    @DeleteMapping("delete")
    @ApiAuth(value = "role.delete",description = "角色删除")
    public Result delete(@RequestParam("id") String id) {
        Result result = ResultTool.success();
        if(id == null || id.isEmpty()){
            return ResultTool.fail(ResultCode.PARAM_NOT_COMPLETE);
        }
        AdminUserExample adminUserExample = new AdminUserExample();
        AdminUserExample.Criteria criteria = adminUserExample.createCriteria();
        criteria.andRoleIdEqualTo(id);
        criteria.andIsDeletedEqualTo(IsDelete.FALSE.getCode());
        if (!adminUserService.selectByExample(adminUserExample).isEmpty()) {
            result = ResultTool.fail(ResultCode.DATA_REPEAT);
            result.setMsg("该角色已被使用,无法删除");
            return result;
        }
        Transaction trans = null;
        try {
            trans= TransUtils.getTrans();
            trans.begin();
            //删除角色
            roleService.delete(id,false);
            //删除角色接口权限
            rolePermissionService.deleteByRoleId(id);
            //删除角色菜单权限
            roleElementService.deleteByRoleId(id);
            trans.commit();
        } catch (Exception e) {
            TransUtils.rollback(trans);
            result = ResultTool.fail();
            logger.error(e.getMessage(), ExceptionUtils.getFullStackTrace(e));
            return result;
        }
        return result;
    }
}
